package com.dingwei.superiordiary.ui.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.dingwei.superiordiary.R;
import com.dingwei.superiordiary.adapter.easyViewHolder.FindListAdapter;
import com.dingwei.superiordiary.app.MyApplication;
import com.dingwei.superiordiary.bean.IndexAttentionBean;
import com.dingwei.superiordiary.mvp.presenter.indexAttentionPresenter;
import com.dingwei.superiordiary.mvp.view.Contract;
import com.dingwei.superiordiary.picktimedialog.PickTimeDialog;
import com.dingwei.superiordiary.picktimedialog.TimePickerView;
import com.dingwei.superiordiary.picktimedialog.listener.IPickTimeDialogListener;
import com.dingwei.superiordiary.picktimedialog.model.VehicleTraceTime;
import com.dingwei.superiordiary.ui.activity.CommodityDetailsActivity;
import com.dingwei.superiordiary.ui.activity.FindDetailsActivity;
import com.dingwei.superiordiary.ui.activity.ForwardEditingActiivty;
import com.dingwei.superiordiary.ui.activity.LoginActivity;
import com.dingwei.superiordiary.ui.activity.ReleaseCommunityActivity;
import com.dingwei.superiordiary.ui.activity.WebViewActivity;
import com.dingwei.superiordiary.utils.ScrollCalculatorHelper;
import com.jude.easyrecyclerview.decoration.DividerDecoration;
import com.lihao.baselibrary.base.BaseActivity;
import com.lihao.baselibrary.base.LazyLoadFragment;
import com.lihao.baselibrary.utils.DisplayUtil;
import com.lihao.baselibrary.utils.L;
import com.lihao.baselibrary.utils.ScreenUtils;
import com.lihao.baselibrary.utils.TimeUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.utils.SocializeUtils;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;
import com.zhouwei.mzbanner.holder.MZViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by lihao on 2018/1/4.
 * 首页-关注
 */

public class IndexAttentionFragment extends LazyLoadFragment implements Contract.IndexAttentionView {
    indexAttentionPresenter indexAttentionPresenter = new indexAttentionPresenter(this);
    @Bind(R.id.m_recyclerView)
    RecyclerView mRecyclerView;
    @Bind(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @Bind(R.id.no_data_layout)
    RelativeLayout noDataLayout;
    @Bind(R.id.no_net_btn)
    TextView noNetBtn;
    @Bind(R.id.no_net_layout)
    RelativeLayout noNetLayout;
    @Bind(R.id.img_filter)
    ImageView imgFilter;
    @Bind(R.id.img_add_post)
    ImageView imgAddPost;

    private int page = 1;
    private String type;
    private FindListAdapter adapter;
    private FindFragmentHeaderView headerView;
    private LinearLayoutManager layoutManager;
    private ScrollCalculatorHelper scrollCalculatorHelper;
    boolean mFull = false;
    List<IndexAttentionBean.DataBean.BannerBean> list = new ArrayList<>();

    //*****************主要代码********************
    //接收数据
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }


    @Override
    protected int setContentView() {
        return R.layout.fragment_find_test;
    }

    @Override
    protected void setBindView() {
        ButterKnife.bind(this, view);
        initView();
    }

    private void initView() {
        type = getArguments().getString("id");
        L.e("type = " + getArguments().getString("id"));
        if (type.equals("1")) {
            imgFilter.setVisibility(View.GONE);
        } else {
            imgFilter.setVisibility(View.GONE);
        }


        headerView = new FindFragmentHeaderView();
        adapter = new FindListAdapter(BaseActivity.context);
        layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.addItemDecoration(new DividerDecoration(getResources().getColor(R.color.bg), DisplayUtil.dip2px(getActivity(), 8)));
        mRecyclerView.setNestedScrollingEnabled(false);
        adapter.addHeader(headerView);

        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                page = page + 1;
                indexAttentionPresenter.initData(page, type, false, false, "", "");
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                indexAttentionPresenter.initData(page, type, true, false, "", "");
            }
        });


        headerView.banner.setBannerPageClickListener(new MZBannerView.BannerPageClickListener() {
            @Override
            public void onPageClick(View view, int i) {

                IndexAttentionBean.DataBean.BannerBean imgListBean = list.get(i);
                if (imgListBean.type.equals("1")) {
                    intent = new Intent(BaseActivity.context, WebViewActivity.class);
                    intent.putExtra("url", imgListBean.parma);
                    intent.putExtra("title", "详情");
                    startActivity(intent);
                } else if ((imgListBean.type.equals("2"))){
                    intent = new Intent(BaseActivity.context, CommodityDetailsActivity.class);
                    intent.putExtra("id", imgListBean.parma);
                    startActivity(intent);
                }else {
                    intent = new Intent(BaseActivity.context, FindDetailsActivity.class);
                    intent.putExtra("id", imgListBean.parma);
                    startActivity(intent);
                }

            }
        });


        //限定范围为屏幕一半的上下偏移180
//        int playTop = CommonUtil.getScreenHeight(getActivity()) / 2 - CommonUtil.dip2px(getActivity(), 130);
//        int playBottom = CommonUtil.getScreenHeight(getActivity()) / 2 + CommonUtil.dip2px(getActivity(), 130);
        int playTop = ScreenUtils.getScreenHeight(BaseActivity.context) / 4;
        int playBottom = ScreenUtils.getScreenHeight(BaseActivity.context) / 4 * 3;
        //自定播放帮助类
        scrollCalculatorHelper = new ScrollCalculatorHelper(R.id.video_item_player, playTop, playBottom);

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            int firstVisibleItem, lastVisibleItem;

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                scrollCalculatorHelper.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                firstVisibleItem = layoutManager.findFirstVisibleItemPosition();
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();

                //这是滑动自动播放的代码
                if (!mFull) {
                    scrollCalculatorHelper.onScroll(recyclerView, firstVisibleItem, lastVisibleItem, lastVisibleItem - firstVisibleItem + 1);
                }
            }
        });

        adapter.xxInterfaceListener(new FindListAdapter.xxInterFace() {
            @Override
            public void showRightDialog(int position, View view) {
                IndexAttentionBean.DataBean.ListBean bean = adapter.getItem(position);
                indexAttentionPresenter.showSortPopupWindow(view, bean.id, position);
            }

            @Override
            public void showShareDialog(int position, View view) {
                IndexAttentionBean.DataBean.ListBean bean = adapter.getItem(position);
                share_id = bean.id;
                indexAttentionPresenter.showSharePopupWindow(view, bean, position, shareListener);
            }

            @Override
            public void likes(int position) {
                IndexAttentionBean.DataBean.ListBean bean = adapter.getItem(position);
                indexAttentionPresenter.like(bean.id, position);
            }

            @Override
            public void forward(int position) {
                IndexAttentionBean.DataBean.ListBean bean = adapter.getItem(position);
                intent = new Intent(BaseActivity.context, ForwardEditingActiivty.class);
                intent.putExtra("bean", bean);
                startActivity(intent);
            }

            @Override
            public void attentionAction(int position) {
                IndexAttentionBean.DataBean.ListBean bean = adapter.getItem(position);
                if (bean.attentioned == 0) {
                    indexAttentionPresenter.attentionAction(bean.consumer_id, "1", position);
                } else {
                    indexAttentionPresenter.attentionAction(bean.consumer_id, "0", position);
                }
            }

        });

    }


    @Override
    protected void lazyLoad() {
        refreshLayout.autoRefresh();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    @Override
    public void OnRefresh(boolean isRefresh, IndexAttentionBean bean) {
        refreshLayout.finishRefresh();
        if (bean.data.banner != null && bean.data.banner.size() > 0) {
            list.clear();
            list.addAll(bean.data.banner);
            list.addAll(bean.data.banner);
            list.addAll(bean.data.banner);
            headerView.banner.setIndicatorVisible(false);
            headerView.banner.setDelayedTime(5000);
            // 设置数据
            headerView.banner.setPages(list, new MZHolderCreator<BannerViewHolder>() {
                @Override
                public BannerViewHolder createViewHolder() {
                    return new BannerViewHolder();
                }
            });
            headerView.banner.start();
        }
        if (bean.data.list != null && bean.data.list.size() > 0) {
            adapter.clear();
            adapter.addAll(bean.data.list);
            showData("success");
        } else {
            showData("no_data");
        }
    }


    @Override
    public void OnLoadMore(boolean isRefresh, IndexAttentionBean bean) {
        adapter.addAll(bean.data.list);
        refreshLayout.finishLoadmore();
        showData("success");
    }

    @Override
    public void OnFail() {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
        showData("fail");
    }

    @Override
    public void likeSuccess(int position) {
        if (adapter.getItem(position).is_likes == 0) {
            adapter.getItem(position).likes = (Integer.parseInt(adapter.getItem(position).likes) + 1) + "";
            adapter.getItem(position).is_likes = 1;
        } else {
            adapter.getItem(position).likes = (Integer.parseInt(adapter.getItem(position).likes) - 1) + "";
            adapter.getItem(position).is_likes = 0;
        }
        adapter.notifyDataSetChanged();

    }

    @Override
    public void hateSuccess(int position) {
        adapter.remove(position);
    }

    @Override
    public void attentionActionSuccess(int position) {
        IndexAttentionBean.DataBean.ListBean bean = adapter.getItem(position);
        bean.attentioned = bean.attentioned == 0 ? 1 : 0;
        adapter.notifyDataSetChanged();
    }

    @Override
    public void collectSuccess(int position) {
        showToast("收藏成功");
    }

    private void showData(String state) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
        if (state.equals("success")) {
            refreshLayout.setVisibility(View.VISIBLE);
            noDataLayout.setVisibility(View.GONE);
            noNetLayout.setVisibility(View.GONE);
        } else if (state.equals("no_data")) {
            refreshLayout.setVisibility(View.GONE);
            noDataLayout.setVisibility(View.VISIBLE);
            noNetLayout.setVisibility(View.GONE);
        } else {
            refreshLayout.setVisibility(View.GONE);
            noDataLayout.setVisibility(View.GONE);
            noNetLayout.setVisibility(View.VISIBLE);
        }
    }

    @OnClick({R.id.no_net_btn, R.id.img_add_post, R.id.img_filter})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.no_net_btn:
                page = 1;
                indexAttentionPresenter.initData(page, type, true, true, "", "");
                break;
            case R.id.img_add_post:
                if (BaseActivity.value.getIsLogin()) {
                    intent = new Intent(BaseActivity.context, ReleaseCommunityActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(BaseActivity.context, LoginActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.img_filter:
                final PickTimeDialog pickDilog = new PickTimeDialog(getActivity())
                        .setType(TimePickerView.Type.YEAR_MONTH_DAY)
                        .setOnPickTimeDialogListener(new IPickTimeDialogListener() {
                            @Override
                            public void onSelected(Object object) {
                                VehicleTraceTime vehicleTraceTime = (VehicleTraceTime) object;
                                page = 1;
                                indexAttentionPresenter.initData(page, type, true, true, TimeUtils.date2String(vehicleTraceTime.getStartTime().getTime()).split(" ")[0], TimeUtils.date2String(vehicleTraceTime.getStartTime().getTime()).split(" ")[0]);

                            }
                        }).create().cantlable().setOnKeyListener(new PickTimeDialog.onKeyListener() {
                            @Override
                            public void run(DialogInterface dialog, int keyCode, KeyEvent event) {
                                dialog.dismiss();
                            }
                        });
                break;
        }
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //如果旋转了就全屏
        if (newConfig.orientation != ActivityInfo.SCREEN_ORIENTATION_USER) {
            mFull = false;
        } else {
            mFull = true;
        }

    }

    @Override
    public void onPause() {
        super.onPause();
        GSYVideoManager.onPause();
        headerView.banner.pause();//暂停轮播
    }

    @Override
    public void onResume() {
        super.onResume();
        GSYVideoManager.onResume();
        headerView.banner.start();//开始轮播
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        GSYVideoPlayer.releaseAllVideos();
    }

    public static class BannerViewHolder implements MZViewHolder<IndexAttentionBean.DataBean.BannerBean> {
        private ImageView mImageView;

        @Override
        public View createView(Context context) {
            // 返回页面布局
            View view = LayoutInflater.from(context).inflate(R.layout.item_index_banner, null);
            mImageView = (ImageView) view.findViewById(R.id.img);
            return view;
        }

        @Override
        public void onBind(Context context, int position, IndexAttentionBean.DataBean.BannerBean data) {
            // 数据绑定
            Glide.with(BaseActivity.context)
                    .load(data.icon)
                    .apply(MyApplication.options)
                    .into(mImageView);

        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(getActivity()).onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case 0:
                page = 1;
                indexAttentionPresenter.initData(page, type, true, false, "", "");
                break;
        }
    }

    String share_id;
    private UMShareListener shareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
            SocializeUtils.safeShowDialog(dialog);
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            Toast.makeText(getActivity(), "分享成功", Toast.LENGTH_SHORT).show();
            SocializeUtils.safeCloseDialog(dialog);
            indexAttentionPresenter.shareSuccess(share_id);

        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            SocializeUtils.safeCloseDialog(dialog);
            Toast.makeText(getActivity(), "分享失败" + t.getMessage(), Toast.LENGTH_LONG).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            SocializeUtils.safeCloseDialog(dialog);
            Toast.makeText(getActivity(), "取消分享", Toast.LENGTH_LONG).show();

        }
    };
}
